import 'package:flutter/material.dart';

class ImagesAnim extends StatefulWidget {
  final double width;
  final double height;
  final bool isLoop;
  final int duration;
  final int animType; //1. 私聊语音播放
  final Color? color; //颜色

  const ImagesAnim(
      {required this.width,
      required this.height,
      required this.animType,
      this.isLoop = false,
      this.duration = 20,
      this.color,
      Key? key})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _AnimImageState();
  }
}

class _AnimImageState extends State<ImagesAnim>
    with SingleTickerProviderStateMixin {
  late Map<int, Widget> imageCaches;
  late AnimationController controller;
  late Animation animation;

  @override
  void initState() {
    super.initState();

    imageCaches = <int, Widget>{};
    setImages();

    controller = AnimationController(
        duration: Duration(milliseconds: widget.duration * imageCaches.length),
        vsync: this);
    animation =
        IntTween(begin: 0, end: imageCaches.length - 1).animate(controller);
    controller.repeat();
  }

  @override
  void dispose() {
    controller.dispose();
    imageCaches.clear();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      height: widget.height,
      color: Colors.transparent,
      child: AnimatedBuilder(
          animation: animation,
          builder: (_, __) {
            return imageCaches[animation.value]!;
          }),
    );
  }

  Image _image(String img, {BoxFit fit = BoxFit.contain}) {
    return Image.asset(
      img,
      gaplessPlayback: true,
      fit: fit,
      color: widget.color,
    );
  }

  void setImages() {
    if (widget.animType == 1) {
      for (int i = 0; i <= 15; i++) {
        imageCaches.putIfAbsent(i, () {
          if (i < 10) {
            return _image('assets/images/animation/sound/00$i.png',
                fit: BoxFit.contain);
          } else {
            return _image('assets/images/animation/sound/0$i.png',
                fit: BoxFit.contain);
          }
        });
      }
    }
  }
}
